<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>闭包</title>
    <style>
        div {
            margin: 5px;
            width: 100px;
            height: 20px;
            color: white;
            background-color: blueviolet;
            text-align: center;
            line-height: 20px;
        }

        div:hover {
            cursor: grab;
        }
    </style>
</head>

<body>
    <h1>闭包</h1>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <script>
        var Counter = (function () {
            var privateCounter = 0;
            function changeBy(val) {
                privateCounter += val;
            }
            return {
                increment: function () {
                    changeBy(1);
                },
                decrement: function () {
                    changeBy(-1);
                },
                value: function () {
                    return privateCounter;
                }
            }
        })();

        console.log(Counter.value()); /* logs 0 */
        Counter.increment();
        Counter.increment();
        console.log(Counter.value()); /* logs 2 */
        Counter.decrement();
        console.log(Counter.value()); /* logs 1 */


        var nodes = document.getElementsByTagName('div');
        for (var i = 0, len = nodes.length; i < len; i++) {
            (function (i) {
                nodes[i].onclick = function () {
                    console.log(i + 1);
                };
            })(i);
        };

        var mult = (function () {
            var cache = {};
            return function () {
                var args = Array.prototype.join.call(arguments, ',');
                if (args in cache) {
                    return cache[args];
                }
                var a = 1;
                for (var i = 0, l = arguments.length; i < l; i++) {
                    a = a * arguments[i];
                }
                return cache[args] = a;
            }
        })();
    </script>
</body>

</html>